//
//  HMultiSelectView.m
//  NursingManages
//
//  Created by Zhen Huang on 17/9/27.
//  Copyright © 2017年 huangzhen. All rights reserved.
//

#import "HMultiSelectView.h"

#import "UIView+SDAutoLayout.h"
#import "MyExamTableViewCell.h"

#import "MyExamHeaderView.h"
#import "Model_Hr_Question_Item.h"

#import "Header.h"
#import "DIHTest.h"
#import "HCommon.h"
#import "HShowALLQuesView.h"
#import "Model_Hr_ExamContent.h"
#import "InitDbTableExamOnLine.h"
#import "HBaseViewController.h"

@interface HMultiSelectView ()<UITableViewDelegate, UITableViewDataSource,PassValueDelegate>

@property (strong, nonatomic) MyExamHeaderView *myExamHeaderView;

@property (strong, nonatomic) UITableView      *tableView;


//多选答案放进数组
@property (strong, nonatomic) NSMutableArray   *sumArray;

@property (nonatomic ,copy) NSString *title;
@property (nonatomic, strong) Model_Hr_Question_Item *model;

@property (nonatomic, strong) UIView *footview;

@property (nonatomic, strong) UIButton *sureButton;

@property (nonatomic, strong) UILabel *label;

@property (nonatomic, strong) UIButton *pageButton;

@property (nonatomic, assign) NSInteger pageIndex;

@property (nonatomic, strong) NSArray *dataArray;

@property (nonatomic, strong) UIImageView *rightImage;

@property (nonatomic, strong) UIImageView *wrongImage;

@property (nonatomic, strong) UIButton *rightButton;

@property (nonatomic, strong) UIButton *wrongButton;

@property (nonatomic, strong) NSMutableArray *rightArray;

@property (nonatomic, strong) NSMutableArray *wrongArray;

@property (nonatomic, strong) UIButton *deleteButton;

@property (nonatomic, strong) UIButton *nextButton;

@property (nonatomic, strong) Model_Hr_ExamContent *contentModel;

@property (nonatomic, strong) Model_Hr_ExamAnswer *examModel;


@property (nonatomic, copy) NSString *res_id;

@property (nonatomic, strong) NSMutableArray *examDetailArray;

@end

@implementation HMultiSelectView

- (instancetype)initWithconfigure:(NSInteger)index
                        dataArray:(NSArray *)dataArray
                       headHeight:(CGFloat)height
                        headTitle:(NSString *)title
                           typeid:(NSString *)type_id
                       onlineArra:(NSArray *)onlineArray
                           res_id:(NSString *)res_id
                       examDetail:(NSArray *)examDetail{
    
    self = [super init];
    if (self) {
        Model_Hr_Question_Item *model = dataArray[index];
//        Model_Hr_ExamContent *contentModel = onlineArray[index];
        Model_Hr_ExamAnswer *answer = examDetail[index];
        self.examModel = answer;
//        self.contentModel = contentModel;
        self.model = model;
        self.title = title;
        self.dataArray = dataArray;
        self.pageIndex = index;
        self.res_id = res_id;
        self.examDetailArray = (NSMutableArray *)examDetail;
        self.rightArray = [NSMutableArray new];
        self.wrongArray = [NSMutableArray new];
        [self initData];
        [self initView];
        
    }
    return self;
}

- (void)initView {
    
    [self addSubview:self.tableView];
    
    _tableView.tableHeaderView = self.myExamHeaderView;
    CGRect newFrame = self.myExamHeaderView.frame;
    // 获取不确定文字的高度
    self.myExamHeaderView.subjectTypeLabel.text = @"多选题";
    self.myExamHeaderView.subjectTypeLabel.textColor = [UIColor colorWithRed:0.95 green:0.58 blue:0.17 alpha:1.00];
    self.myExamHeaderView.subjectTypeLabel.layer.borderColor =[UIColor colorWithRed:0.95 green:0.58 blue:0.17 alpha:1.00].CGColor;
    _myExamHeaderView.subjectLabel.text = self.title;
    CGFloat testHeight = [self sizeWithFont:[UIFont systemFontOfSize:17.0] maxW:ScreenWidth-67 withContent:_myExamHeaderView.subjectLabel.text] ;
    newFrame.size.height =   testHeight+60;
    self.myExamHeaderView.frame = newFrame;
    
    [self.tableView beginUpdates];
    
    [self.tableView setTableHeaderView: self.myExamHeaderView];
    [self.tableView setTableFooterView:self.footview];
    [self.tableView endUpdates];
    
}

- (void)initData {
    
    [self sumArray];
    
    
}

- (void)setSeleIndexStr:(NSMutableArray *)seleIndexStr {
    
    _seleIndexarr = seleIndexStr;
    
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return self.model.optionArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *string   = @"UITableViewCell";
    
    MyExamTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:string];
    
    cell.selectedBtn.selected = NO;

    
    if (!cell) {
        
        cell = [[MyExamTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:string];
    }
    
    if (self.examModel.RES_ANSWER != nil) {
        
        [self.footview addSubview:self.nextButton];
        
        [self.footview addSubview:self.deleteButton];
        
        self.sureButton.hidden = YES;
        
        self.deleteButton.hidden  = NO;
        
        self.nextButton.hidden = NO;
        
    }else {
        
        [self.footview addSubview:self.sureButton];
        
        self.nextButton.hidden = YES;
        
        self.deleteButton.hidden = YES;
        
        self.sureButton.hidden = NO;
    }

    
    
    
    
    [self.rightArray removeAllObjects];
    [self.wrongArray removeAllObjects];
    
    for (Model_Hr_ExamAnswer *model in self.examDetailArray) {
        
        if (model.RES_ANSWER != nil) {
            
            if ([model.RES_ANSWER isEqualToString:self.model.ANSWER]) {
                
                [self.rightArray addObject:model];
            }else {
                [self.wrongArray addObject:model];
            }
        }
    }
    
//    [self.rightButton setTitle:[NSString stringWithFormat:@"%ld",self.rightArray.count?:0] forState:UIControlStateNormal];
//    
//    [self.wrongButton setTitle:[NSString stringWithFormat:@"%ld",self.wrongArray.count?:0] forState:UIControlStateNormal];
    
    NSMutableArray *array = [NSMutableArray new];
    
    for (int i = 0; i < self.examModel.RES_ANSWER.length; i ++) {
        
        NSString *answer = [self.examModel.RES_ANSWER substringWithRange:NSMakeRange(i, 1)];
        
        [array addObject:answer];
        
    }
    
    if (self.examModel.RES_ANSWER != nil) {
        
        cell.userInteractionEnabled = NO;
        
//        if ([self.model.ANSWER isEqualToString:self.model.answers]) {
//            
//            self.label.textColor = RGB(69, 185, 124);
//            
//            self.label.text = @"回答正确";
//            
//        }else {
//            self.label.textColor = [UIColor redColor];
//            
//            self.label.text = [NSString stringWithFormat:@"回答错误,正确答案:%@",self.model.ANSWER];
//            
//            
//        }
        
    }else {
        
        cell.userInteractionEnabled = YES;
        
    }
    
    NSString *option = self.model.optionArray[indexPath.row];
    
    switch (indexPath.row) {
            
        case 0:
            [cell.selectedBtn setTitle:@"A" forState:UIControlStateNormal];
            cell.selectedBtn.tag = 1;
            break;
        case 1:
            [cell.selectedBtn setTitle:@"B" forState:UIControlStateNormal];
            cell.selectedBtn.tag = 2;
            break;
        case 2:
            [cell.selectedBtn setTitle:@"C" forState:UIControlStateNormal];
            cell.selectedBtn.tag = 3;
            break;
        case 3:
            [cell.selectedBtn setTitle:@"D" forState:UIControlStateNormal];
            cell.selectedBtn.tag = 4;
            break;
        case 4:
            [cell.selectedBtn setTitle:@"E" forState:UIControlStateNormal];
            cell.selectedBtn.tag = 5;
            break;
        case 5:
            [cell.selectedBtn setTitle:@"F" forState:UIControlStateNormal];
            cell.selectedBtn.tag = 5;
            break;
        case 6:
            [cell.selectedBtn setTitle:@"G" forState:UIControlStateNormal];
            cell.selectedBtn.tag = 5;
            break;
        case 7:
            [cell.selectedBtn setTitle:@"H" forState:UIControlStateNormal];
            cell.selectedBtn.tag = 5;
            break;
        case 8:
            [cell.selectedBtn setTitle:@"I" forState:UIControlStateNormal];
            cell.selectedBtn.tag = 5;
            break;
        case 9:
            [cell.selectedBtn setTitle:@"J" forState:UIControlStateNormal];
            cell.selectedBtn.tag = 5;
            break;
            
        default:
            break;
    }
    
    
    if (array.count > 0) {
        
        for (NSString *i in array) {
            if ([i isEqualToString:[NSString stringWithFormat:@"%@",cell.selectedBtn.titleLabel.text]]) {
                cell.selectedBtn.selected = YES;
            }
        }
    }
    //选项的弧度
    cell.selectedBtn.layer.cornerRadius = 5;
    cell.selectlable.text = option;
    
    return cell;
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return 50;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    
    return CGFLOAT_MIN;
}


- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    
    return 0.01;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    MyExamTableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    
    cell.selectedBtn.selected = !cell.selectedBtn.selected;
    
    if (![_sumArray containsObject:[NSString stringWithFormat:@"%@",cell.selectedBtn.titleLabel.text]]) {
        
        [_sumArray addObject:[NSString stringWithFormat:@"%@",cell.selectedBtn.titleLabel.text]];
        
    }else {
        
        [_sumArray removeObject:[NSString stringWithFormat:@"%@",cell.selectedBtn.titleLabel.text]];
    }
    
}

- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight - NavBarHeight + 10)style:UITableViewStyleGrouped];
        _tableView.separatorStyle  = UITableViewCellSeparatorStyleNone;
        _tableView.delegate        = self;
        _tableView.dataSource      = self;
        _tableView.backgroundColor = [UIColor whiteColor];
        _tableView.tableFooterView = [[UIView alloc]init];
        
        
    }
    return _tableView;
}

- (MyExamHeaderView *)myExamHeaderView {
    if (!_myExamHeaderView) {
        _myExamHeaderView = [[MyExamHeaderView alloc]init];
    }
    return _myExamHeaderView;
}

- (UIView *)footview
{
    if (!_footview) {
        _footview = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, 110)];

        [_footview addSubview:self.pageButton];
        
    }
    return _footview;
}

- (UILabel *)label
{
    if (!_label) {
        _label = [[UILabel alloc]initWithFrame:CGRectMake(20, 5, ScreenWidth - 40, 30)];
    }
    return _label;
}

- (UIButton *)pageButton
{
    if (!_pageButton) {
        _pageButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _pageButton.frame = CGRectMake(ScreenWidth - 100, self.sureButton.bottom + 5, 80, 20);
        [_pageButton setTitleColor:[UIColor orangeColor] forState:UIControlStateNormal];
        [_pageButton setTitle:[NSString stringWithFormat:@"%ld/%ld",self.pageIndex + 1,self.dataArray.count] forState:UIControlStateNormal];
        _pageButton.contentHorizontalAlignment = 2;
        [_pageButton addTarget:self action:@selector(showAll:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _pageButton;
}


- (UIImageView *)rightImage
{
    if (!_rightImage) {
        _rightImage = [[UIImageView alloc]initWithFrame:CGRectMake(10, self.sureButton.bottom + 5, 20, 20)];
        _rightImage.image = [UIImage imageNamed:@"icon_correct3"];
    }
    return _rightImage;
}
- (UIButton *)rightButton
{
    if (!_rightButton) {
        _rightButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _rightButton.frame = CGRectMake(self.rightImage.right + 5, self.sureButton.bottom + 5, 25, 25);
        [_rightButton addTarget:self action:@selector(showAll:) forControlEvents:UIControlEventTouchUpInside];
        [_rightButton setTitleColor:RGB(69, 185, 124) forState:UIControlStateNormal];
    }
    return _rightButton;
}

- (UIImageView *)wrongImage
{
    if (!_wrongImage) {
        _wrongImage = [[UIImageView alloc]initWithFrame:CGRectMake(70, self.sureButton.bottom + 5, 20, 20)];
        _wrongImage.image = [UIImage imageNamed:@"icon_wrong"];
    }
    return _wrongImage;
}
- (UIButton *)wrongButton
{
    if (!_wrongButton) {
        _wrongButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _wrongButton.frame = CGRectMake(self.wrongImage.right + 5, self.sureButton.bottom + 5, 25, 25);
        [_wrongButton setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
        [_wrongButton addTarget:self action:@selector(showAll:) forControlEvents:UIControlEventTouchUpInside];
        
    }
    return _wrongButton;
}



- (UIButton *)sureButton
{

    if (!_sureButton) {
            _sureButton = [UIButton buttonWithType:UIButtonTypeCustom];
            _sureButton.frame = CGRectMake(10, 40, ScreenWidth - 20, 35);
            _sureButton.layer.masksToBounds = YES;
            _sureButton.layer.cornerRadius = 6;
            [_sureButton setTitle:@"确定" forState:UIControlStateNormal];
            _sureButton.backgroundColor = kNavBlueColor;
            _sureButton.tag = 1;
            [_sureButton addTarget:self action:@selector(sure:) forControlEvents:UIControlEventTouchUpInside];
        }
    
    
    return _sureButton;
}

- (UIButton *)nextButton
{
    if (!_nextButton) {
        _nextButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _nextButton.frame = CGRectMake(7, 40, (ScreenWidth - 20)/2, 35);
        _nextButton.layer.masksToBounds = YES;
        _nextButton.layer.cornerRadius = 3;
        [_nextButton setTitle:@"继续下一题" forState:UIControlStateNormal];
        _nextButton.backgroundColor = kNavBlueColor;
        _nextButton.tag = 1;
        [_nextButton addTarget:self action:@selector(nexttext:) forControlEvents:UIControlEventTouchUpInside];
    }
    
    return _nextButton;
}


- (UIButton *)deleteButton
{
    if (!_deleteButton) {
        _deleteButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _deleteButton.frame = CGRectMake(self.nextButton.right + 5, 40, (ScreenWidth - 20)/2, 35);
        _deleteButton.layer.masksToBounds = YES;
        _deleteButton.layer.cornerRadius = 3;
        [_deleteButton setTitle:@"更改答案" forState:UIControlStateNormal];
        _deleteButton.backgroundColor = kNavBlueColor;
        _deleteButton.tag = 2;
        [_deleteButton addTarget:self action:@selector(delete:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _deleteButton;
}



- (void)showAll:(UIButton *)sender
{
    HShowALLQuesView *infoView = [[HShowALLQuesView alloc]initWithFrame:CGRectMake(0, ScreenHeight - 500, ScreenWidth, 500)];
    infoView.dataArray = self.dataArray;
    
    infoView.examArray = self.examDetailArray;
    
    infoView.delegate = self;
    
    
    infoView.type = 2;
    
    infoView.isTestOrExam = 2;
    
    infoView.onlyTest = 0;


    [self addSubview:infoView];
    
    UIView *view = [infoView viewWithTag:1000];
    [UIView animateWithDuration:0.5 animations:^{
        view.frame = CGRectMake(0, self.bounds.size.height-500,self.bounds.size.width, 500);
    }];
    
}
- (void)sure:(UIButton *)sender
{
//    if (sender.tag == 1) {
    
        if (self.sumArray.count >= 2) {
            NSArray *resultkArrSort = [self.sumArray sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
                
                return [obj1 compare:obj2 options:NSNumericSearch];
            }];
            NSString *string = [resultkArrSort componentsJoinedByString:@","];
            
            string=[string stringByReplacingOccurrencesOfString:@","withString:@""];
            
            self.examModel.RES_ANSWER = string;
            
//            DIHTest *test = [[DIHTest alloc]init];
            
//            [test modelItem:self.model];
            
            
            self.examModel.QUES_ID = self.model.QUES_ID;
            self.examModel.TYPEID = self.model.TYPEID;
            self.examModel.RES_ANSWER = string;
            self.examModel.RES_ID = self.res_id;
            self.examModel.QUES_SCORE  = self.contentModel.ACTUAL_SCORE;

            if ([self.examModel.RES_ANSWER isEqualToString:self.model.ANSWER]) {
                
                self.examModel.RIGHT_FLAG = 1;
                
            }else {
                
                self.examModel.RIGHT_FLAG = 0;
                                
            }
            
            
            InitDbTableExamOnLine *initOnLine = [[InitDbTableExamOnLine alloc]init];
            
            
            [initOnLine inspectDetailModel:self.examModel];

            
            [self.tableView reloadData];
            
            
        }else {
            
            [HCommon popupErrorMessage:@"请至少选择两个答案"];
        }
        
    }
    
//}

- (void)nexttext:(UIButton *)sender
{
    __weak typeof(self) weakSelf = self;
    
    if (self.MultiSelectBlock) {
        
        self.MultiSelectBlock(weakSelf.sumArray,1,0);
    }
    
}

- (void)delete:(UIButton *)sender {
    
    [self.sumArray removeAllObjects];
    
//    DIHTest *test = [[DIHTest alloc]init];
    
//    [test updateDataWithQuesid:self.model.QUES_ID];
    
//    self.model.answers = nil;
    
    InitDbTableExamOnLine *initDB = [[InitDbTableExamOnLine alloc]init];
    
    [initDB deleteTableWithHSaTableCode:self.contentModel.QUES_ID];

    self.examModel.RES_ANSWER = nil;
    
    [self.tableView reloadData];

}

- (void)passValueByDelegateWithString:(NSInteger )string {
    
    __weak typeof(self) weakSelf = self;
    
    if (self.MultiSelectBlock) {
        
        self.MultiSelectBlock(weakSelf.sumArray,2,string);
    }
    
    
}

- (NSMutableArray *)sumArray {
    if (!_sumArray) {
        _sumArray = [[NSMutableArray alloc]init];
    }
    return _sumArray;
}

// 计算指定文字的高度
-(CGFloat)sizeWithFont:(UIFont *)font maxW:(CGFloat) maxW withContent:(NSString *)testStr{
    
    NSDictionary *textAttrs = @{NSFontAttributeName : font};
    CGSize size = CGSizeMake(maxW, MAXFLOAT);
    return [testStr boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin attributes:textAttrs context:nil].size.height;
}


@end
